import logging
import time
from config import load_config
from serial_bridge import SerialBridge

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('serial_server.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger('MultiSerialServer')

def main():
    bridges = []
    
    try:
        # 加载配置文件
        configs = load_config('serial_config.json')
        #logger.info(f"加载了 {len(configs)} 个串口配置")
        logger.info("加载了 {} 个串口配置".format(
            len(configs)
        ))

        
        # 创建并启动所有桥接服务
        for config in configs:
            try:
                bridge = SerialBridge(config)
                bridge.start()
                bridges.append(bridge)
            except Exception as e:
                #logger.error(f"启动串口 {config.get('serial_port', '未知')} 失败: {str(e)}")
                logger.error("{}: 启动串口 失败: {}".format(
                    config.get('serial_port', '未知'),
                    str(e)
                ))

        
        if not bridges:
            #logger.error("没有有效的串口配置，程序退出")
            logger.error("没有有效的串口配置，程序退出")

            return
        
        logger.info("所有串口服务器已启动，按 Ctrl+C 停止")

        
        # 主循环
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        logger.info("收到中断信号，停止所有服务器")
    except Exception as e:
        #logger.error(f"服务器错误: {str(e)}")
        logger.error("服务器错误: {}".format(
            str(e)
        ))

    finally:
        # 停止所有桥接服务
        for bridge in bridges:
            try:
                bridge.stop()
            except Exception as e:
                logger.error("{}: 停止串口服务器错误: {}".format(
                    bridge.config['serial_port'],
                    str(e)
                ))
                #logger.error(f"停止串口服务器错误: {str(e)}")

if __name__ == '__main__':
    main()